import {PlusOutlined} from '@ant-design/icons';
import {ActionType, ProColumns, ProForm} from '@ant-design/pro-components';
import {PageContainer, ProTable, TableDropdown} from '@ant-design/pro-components';
import {Button, Drawer, Image} from 'antd';
import React, {useEffect, useRef, useState} from 'react';
import {pageQueryAdminUsingGET, queryAdminByIdUsingGET} from "@/services/ant-design-pro/guanliyuanxiangguanjiekou";
import {ModalForm, ProFormSelect, ProFormText, ProFormUploadButton} from "@ant-design/pro-form";
import {TableListItem} from "@/pages/Admin/Fertilizer/data";
import {HEAD_LINK} from "@/constants";

const AdminList = () => {

  // 自定义每页显示多少条的选项
  const pageSizeOptions = ['5', '10', '20', '50'];

  /** 新建窗口的弹窗 */
  const [createModalVisible, handleModalVisible] = useState<boolean>(false);

  const [modalVisible, setModalVisible] = useState(false);
  const [selectId, setSelectId] = useState(null);
  const [userDetail, setUserDetail] = useState({}); // 使用空对象进行初始化 // 新增 userDetail 状态

  const handleViewClick = (adminId) => {
    setModalVisible(true);
    setSelectId(adminId);
  };

  const handleModalClose = () => {
    setModalVisible(false);
    setSelectId(null);
  };

  const actionRef = useRef<ActionType>();

  const fetchUserDetail = async (adminId) => {
    try {
      const userInfo = await queryAdminByIdUsingGET({id: adminId});
      return userInfo.data;
    } catch (error) {
      console.error('获取管理员详情时出错：', error);
      return null;
    }
  };

  useEffect(() => {
    const loadData = async () => {
      if (selectId !== null) {
        const userDetailData = await fetchUserDetail(selectId);
        // console.log(userDetailData)
        setModalVisible(true);
        setSelectId(selectId);
        if (userDetail !== null) {
          // @ts-ignore
          setUserDetail(userDetailData);
        }
        actionRef.current?.reload(); // 重新加载表格数据
      }
    };

    loadData();
  }, [selectId]);

// @ts-ignore
  const columns: ProColumns<API.BaseResultPageQueryCondition_.data.page.recorde>[] = [
    {
      title: 'Id',
      dataIndex: 'adminId',
      // valueType: 'indexBorder',
      width: 70,
      hideInSearch: true
    },
    {
      title: '头像',
      width: 80,
      dataIndex: 'adminHeadpic',
      render: (_, record) => (
        <div>
          <Image src={`${HEAD_LINK}${record.adminHeadpic}`} width={60}/>
        </div>
      ),
      copyable: true,
      hideInSearch: true
    },
    {
      title: '姓名',
      width: 100,
      dataIndex: 'adminName',
      copyable: true,
      ellipsis: true,
      tip: '用户名过长会自动收缩',
    },
    {
      title: '电话📞',
      width: 120,
      dataIndex: 'adminPhone',
      copyable: true,
    },
    {
      title: '邮件',
      dataIndex: 'adminEmail',
      copyable: true,
      ellipsis: true,
      tip: '邮箱过长会自动收缩',
    },
    {
      title: '公司',
      dataIndex: 'adminCompany',
      copyable: true,
      hideInSearch: true
    },
    {
      title: '性别',
      width: 50,
      dataIndex: 'adminGender',
      valueType: 'select',
      valueEnum: {
        0: {text: '女'},
        1: {text: '男'},
      },
      hideInSearch: true
    },
    // {
    //   title: '角色',
    //   dataIndex: 'RoleList.roleId',
    //   valueType: 'select',

    // },
    {
      title: '创建时间',
      width: 150,
      dataIndex: 'createTime',
      valueType: 'dateTime',
      // sorter: true,
      hideInSearch: true
    },
    {
      title: '操作',
      valueType: 'option',
      key: 'option',
      render: (text, record, _, action) => [
        <a
          key="editable"
          onClick={() => {
            action?.startEditable?.(record.adminId);
          }}
        >
          编辑
        </a>,
        <a key="view" onClick={() => handleViewClick(record.adminId)}>
          查看
        </a>,

        <TableDropdown
          key="actionGroup"
          onSelect={() => action?.reload()}
          menus={[
            // {key: 'copy', name: '复制'},
            {key: 'delete', name: '删除'},
          ]}
        />,
      ],
    },
  ];

  // @ts-ignore
  return (
    <PageContainer>
      <ProTable<API.pageQueryAdminUsingGETParams>
        columns={columns}
        actionRef={actionRef}
        cardBordered
        request={async (params, sort, filter) => {
          try {
            console.log('请求参数:', params);  // 打印请求参数

            const userList = await pageQueryAdminUsingGET({
              queryCondition: params.adminName || params.adminPhone || params.adminEmail,  // 将 keyword 包含在请求中
              currentPage: params.current,
              pageSize: params.pageSize,
            });

            // @ts-ignore
            const records = userList.data.page.records;

            return {
              data: records,
              success: true,
              total: userList.data?.page?.total,
            };
          } catch (error) {
            console.error('数据请求出错：', error);
            return {
              success: false,
            };
          }
        }
        }


        editable={{
          type: 'multiple',
        }}
        columnsState={{
          persistenceKey: 'pro-table-singe-demos',
          persistenceType: 'localStorage',
          onChange(value) {
            console.log('value: ', value);
          },
        }}
        rowKey="adminId"


        search={{
          showHiddenNum: true,
          labelWidth: 'auto',
        }}
        options={{
          setting: {
            // listsHeight: 400,
          },
        }}
        form={{
          // 由于配置了 transform，提交的参与与定义的不同这里需要转化一下
          syncToUrl: (values, type) => {
            if (type === 'get') {
              return {
                ...values,
                created_at: [values.startTime, values.endTime],
              };
            }
            return values;
          },
        }}


        pagination={{
          // showQuickJumper: true,
          showSizeChanger: true,
          pageSizeOptions: pageSizeOptions,
          defaultPageSize: 5, // 默认每页显示的条数
          onChange: (page) => console.log(page),
          onShowSizeChange: (current, size) => console.log(current, size),
        }}


        dateFormatter="string"
        headerTitle="用户基本信息"
        toolBarRender={() => [
          <Button
            key="addAdmin"
            icon={<PlusOutlined/>}
            onClick={() => {
              handleModalVisible(true);
            }}
            type="primary"
          >
            添加
          </Button>
        ]}
      />

      <ModalForm
        title="添加用户"
        // width="400px"
        visible={createModalVisible}
        onVisibleChange={handleModalVisible}
        onFinish={async (value) => {
          const success = await handleAdd(value as TableListItem);
          if (success) {
            handleModalVisible(false);
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
      >
        <ProForm.Group>
          <ProFormText
            width="md"
            name="adminName"
            label="姓名"
            placeholder="请输入姓名"
            rules={[{required: true, message: '请输入姓名'}]}
          />

          <ProFormText
            width="md"
            name="adminPhone"
            label="电话"
            placeholder="请输入电话"
            rules={[{required: true, message: '请输入电话'}]}
          />
        </ProForm.Group>
        <ProForm.Group>
          <ProFormText
            width="md"
            name="adminEmail"
            label="邮箱"
            placeholder="请输入邮箱"
          />
          <ProFormText.Password
            width="md"
            name="password"
            label="密码"
            placeholder="请输入密码"
            rules={[{required: true, message: '请输入密码'}]}
          />

        </ProForm.Group>
        <ProForm.Group>
          <ProFormText
            width="md"
            name="company"
            label="公司名称"
            placeholder="请输入公司代码"
          />

          <ProFormSelect
            width="md"
            name="roles"
            label="角色"
            mode="multiple"
            valueEnum={{
              1: {text: '培育人员'},
              2: {text: '检测人员'},
              3: {text: '仓库管理人员'},
              4: {text: '车间加工环节人员'},
              5: {text: '销售人员'},
              6: {text: '人事部门'},
            }}
          />
        </ProForm.Group>

        <ProForm.Group>
          <ProFormSelect
            width="xs"
            name="gender"
            label="性别"
            valueEnum={{
              0: '女',
              1: '男',
            }}
          />

          <ProFormUploadButton
            name="avatar"
            label="头像"
            fieldProps={{
              max: 1, // 限制最多上传一个文件
              listType: 'picture-card', // 可以设置为 'text'，在列表中显示文件名
            }}
            showUploadList={{
              showRemoveIcon: true,
            }}
            action="/your-upload-api" // 上传接口地址

          />
        </ProForm.Group>

      </ModalForm>

      <Drawer
        title="用户详情"
        visible={modalVisible}
        onClose={handleModalClose}
        maskClosable={true}
        width={400} // 根据需要调整宽度
        maskStyle={{ backgroundColor: 'rgba(0, 0, 0, 0.4)' }}
        placement="right" // 从右侧显示
        footer={null} // 如果不需要底部按钮，可以将 footer 设置为 null
      >
        {/* 将 AdminDetail 组件渲染在 Drawer 中 */}
        {modalVisible && <AdminDetail userDetail={userDetail} />}
      </Drawer>


    </PageContainer>
  )
};


// @ts-ignore
const AdminDetail = ({userDetail}) => {
  return (
    <div>
      {userDetail && (
        <div>
          <h2>{userDetail.adminName} 的详情</h2>
          <p>用户ID: {userDetail.adminId}</p>
          <p>邮箱: {userDetail.adminEmail}</p>
          <p>电话: {userDetail.adminPhone}</p>
          <p>公司: {userDetail.adminCompany}</p>
          <p>头像: <img src={`${HEAD_LINK}${userDetail.adminHeadpic}`} alt="头像" style={{maxWidth: '60px'}}/></p>
          <p>性别: {userDetail.adminGender === 0 ? '女' : '男'}</p>
          <p>创建时间: {new Date(userDetail.createTime).toLocaleString()}</p>

          <h3>角色信息：</h3>
          {userDetail && userDetail.roleList && userDetail.roleList.map((role) => (
            <div key={role.roleId}>
              <p>角色ID: {role.roleId}</p>
              <p>角色名称: {role.roleName}</p>
              <p>角色描述: {role.roleDescription}</p>
            </div>
          ))}


          {/* 判断用户是否有效 */}
          <p>用户状态: {userDetail.delete ? '有效' : '无效'}</p>
        </div>
      )}

    </div>
  );
};


export default AdminList;

